import styles from './index.less';
import React, { useEffect, useState } from 'react';
import TopHeader from './TopHeader';
import Slider from './Slider';
import { history, connect } from 'umi';
import { Layout, Button, Card, message } from 'antd';
const { Content } = Layout;
import classNames from 'classnames/bind';
let cx = classNames.bind(styles);
import { getUrl } from '@/utils/common';
import { getAppSearch } from '@/servers/common';
import Microapp from '@/commonts/Microapp';
import { ConfigProvider } from 'antd';
import zhCN from 'antd/es/locale/zh_CN';
import actions from '@/shared/actions';
import PageTabs from './PageTabs';
import { ImuneTreeArr } from '@/types/common';

const Index = (props: any) => {
  const { children, common } = props;

  /**
   * 子应用选择要删除掉的页签
   */
  const [activePath, setActivePath] = useState<string>('');

  useEffect(() => {
    appList();
  }, []);

  // 内容区域
  const contentData = () => {
    const pathName1 = history.location.pathname.split('/')[1];
    // 当前路由名称
    const pathName2 = history.location.pathname.split('/')[2] || '';
    // 存储工作台首页，基座本身权限管理数据
    const pathArr: string[] = [
      'Home',
      'userAdmin',
      'appList',
      'publicApp',
      'publicApp2',
    ];

    // 如果当前路由在属于基座里路由的情况下
    if (pathArr.includes(pathName1) || pathArr.includes(pathName2)) {
      return children;
    } else {
      return (
        <div>
          <Card title="基座通信区域">
            <div className={styles.microappMaster}>
              <div>我是基座</div>
              <Button onClick={btn} type="primary">
                发送数据到子应用
              </Button>
              接收子应用传递过来的消息 {common.count}
            </div>
          </Card>

          <Card title="微应用页面区域">
            <Microapp></Microapp>
          </Card>
        </div>
      );
    }
  };

  // 根据当前url查询到当前所在应用信息
  const appList = async () => {
    if (JSON.stringify(common.presentApp) === '{}') {
      const res = await getAppSearch({ appName: getUrl() });

      // 通过dispatch 调用文件下的save 改变dva 下 system 的 state的状态值
      props.dispatch({
        type: 'common/save',
        payload: {
          presentApp: res.data[0],
        },
      });
    }
  };

  /**
   * 更新计数器
   */
  const btn = async () => {
    props.dispatch({
      type: 'common/save',
      payload: {
        count: common.count + 1,
      },
    });
  };

  useEffect(() => {
    /**
     * 发送消息到子应用
     */
    actions.setGlobalState({
      // 计数
      count: common.count,
      // 当前路径
      activePath: '',
    });
  }, [common.count]);

  /**
   * 监听全局 接收子组件发送过来的数据
   */
  useEffect(() => {
    actions.onGlobalStateChange((state: any) => {
      const { count, activePath } = state;
      props.dispatch({
        type: 'common/save',
        payload: {
          count: count ? count : 0,
        },
      });
      setActivePath(activePath);
    });
  }, []);

  /**
   * 监听 activePath 的变化 删除页签操作
   */
  useEffect(() => {
    if (!activePath) return;

    const menuBarArr = [...common?.menubar];
    if (menuBarArr.length === 1) {
      message.info('已是最后一项');
      return;
    }
    // 查询当前要删除的页签项在页签数组里的位置  根据路由判断 path
    const Zindex = menuBarArr?.findIndex((item: ImuneTreeArr) => item.path === activePath);
    menuBarArr.splice(Zindex, 1);

    // 删除的是第一项那么选中项往后推 不是则 往前推
    const arrIndex = Zindex === 0 ? 0 : Zindex - 1; // 获取删除的前一个下标索引

    // 查询当前项在总菜单数组里的位置
    const Zindex2 = common?.menuTreeList?.findIndex((item: ImuneTreeArr) => item.id === common?.menubar[arrIndex].id);

    props.dispatch({
      type: 'common/save',
      payload: {
        numberZindex: arrIndex,
        menubar: [...menuBarArr],
        defaultSelected: [`${Zindex2 + 1}`]
      },
    });
    // 跳转都删除操作之后应该跳转的页面
    history.push(menuBarArr[arrIndex].path);

  }, [activePath])

  return (
    <ConfigProvider locale={zhCN}>
      <TopHeader />
      {history.location.pathname !== '/Home' && <Slider />}

      <Content
        className={cx({
          content: history.location.pathname !== '/Home',
          contents: history.location.pathname === '/Home',
        })}
      >
        {
          history.location.pathname !== '/Home' && <PageTabs />
        }
        {contentData()}
      </Content>
    </ConfigProvider>
  );
};

export default connect(({ common }: any) => ({ common }))(Index);
